<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>历史行情查询</title>
	<link rel="stylesheet" href="https://unpkg.com/element-ui@2.13.0/lib/theme-chalk/index.css">
	<link rel="stylesheet" href="../../static/sa.css">
	<script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js"></script>
	<style>
		.history-container {
			padding: 20px;
			max-width: 1400px;
			margin: 0 auto;
		}
		.search-panel {
			background: #fff;
			border-radius: 12px;
			box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
			padding: 25px;
			margin-bottom: 25px;
		}
		.search-title {
			font-size: 18px;
			font-weight: 600;
			color: #333;
			margin-bottom: 20px;
			display: flex;
			align-items: center;
			gap: 10px;
		}
		.search-form {
			display: grid;
			grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
			gap: 20px;
			align-items: end;
		}
		.form-item {
			display: flex;
			flex-direction: column;
			gap: 8px;
		}
		.form-label {
			font-weight: 500;
			color: #333;
			font-size: 14px;
		}
		.results-panel {
			background: #fff;
			border-radius: 12px;
			box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
			margin-bottom: 25px;
		}
		.results-header {
			background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
			color: white;
			padding: 20px 25px;
			border-radius: 12px 12px 0 0;
			display: flex;
			justify-content: space-between;
			align-items: center;
		}
		.results-title {
			font-size: 18px;
			font-weight: 600;
			display: flex;
			align-items: center;
			gap: 10px;
		}
		.results-content {
			padding: 25px;
		}
		.chart-tabs {
			margin-bottom: 20px;
		}
		.chart-container {
			height: 400px;
			width: 100%;
			margin-bottom: 20px;
		}
		.data-table {
			margin-top: 20px;
		}
		.statistics-summary {
			display: grid;
			grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
			gap: 15px;
			margin-bottom: 20px;
		}
		.summary-item {
			background: #f8f9fa;
			padding: 15px;
			border-radius: 8px;
			text-align: center;
			border-left: 4px solid #409eff;
		}
		.summary-value {
			font-size: 20px;
			font-weight: bold;
			color: #409eff;
			margin-bottom: 5px;
		}
		.summary-label {
			color: #666;
			font-size: 12px;
		}
		.compare-section {
			background: #fff;
			border-radius: 12px;
			box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
			padding: 25px;
			margin-bottom: 25px;
		}
		.compare-title {
			font-size: 18px;
			font-weight: 600;
			color: #333;
			margin-bottom: 20px;
			display: flex;
			align-items: center;
			gap: 10px;
		}
		.compare-controls {
			display: flex;
			gap: 15px;
			margin-bottom: 20px;
			flex-wrap: wrap;
			align-items: center;
		}
		.compare-chart {
			height: 300px;
			width: 100%;
		}
		.export-section {
			text-align: right;
			margin-top: 20px;
			padding-top: 20px;
			border-top: 1px solid #e9ecef;
		}
		.trend-indicator {
			display: inline-flex;
			align-items: center;
			gap: 4px;
			padding: 2px 6px;
			border-radius: 4px;
			font-size: 12px;
			font-weight: 500;
		}
		.trend-up {
			background: #f0f9ff;
			color: #0369a1;
		}
		.trend-down {
			background: #fef2f2;
			color: #dc2626;
		}
		.trend-stable {
			background: #f0fdf4;
			color: #166534;
		}
		.loading-state {
			text-align: center;
			padding: 60px 20px;
			color: #999;
		}
		.no-data {
			text-align: center;
			padding: 60px 20px;
			color: #999;
		}
	</style>
</head>
<body>
	<div id="app" v-cloak>
		<div class="history-container">
			<!-- 页面标题 -->
			<div class="page-title">
				<h2>历史行情查询</h2>
				<p>按时间、品类回溯历史行情数据，分析市场趋势</p>
			</div>

			<!-- 查询面板 -->
			<div class="search-panel">
				<div class="search-title">
					<i class="el-icon-search"></i>
					行情查询条件
				</div>
				<div class="search-form">
					<div class="form-item">
						<label class="form-label">商品品类</label>
						<el-select v-model="searchForm.category" placeholder="选择品类" multiple collapse-tags>
							<el-option label="生鲜蔬菜" value="vegetable"></el-option>
							<el-option label="精品肉类" value="meat"></el-option>
							<el-option label="海鲜水产" value="seafood"></el-option>
							<el-option label="冷冻食品" value="frozen"></el-option>
							<el-option label="乳制品" value="dairy"></el-option>
							<el-option label="新鲜水果" value="fruit"></el-option>
						</el-select>
					</div>
					<div class="form-item">
						<label class="form-label">具体商品</label>
						<el-select v-model="searchForm.product" placeholder="选择商品" multiple collapse-tags>
							<el-option v-for="product in availableProducts" :key="product.value" :label="product.label" :value="product.value"></el-option>
						</el-select>
					</div>
					<div class="form-item">
						<label class="form-label">地区范围</label>
						<el-select v-model="searchForm.region" placeholder="选择地区">
							<el-option label="全国" value="national"></el-option>
							<el-option label="华北地区" value="north"></el-option>
							<el-option label="华东地区" value="east"></el-option>
							<el-option label="华南地区" value="south"></el-option>
							<el-option label="华中地区" value="central"></el-option>
							<el-option label="西南地区" value="southwest"></el-option>
							<el-option label="西北地区" value="northwest"></el-option>
							<el-option label="东北地区" value="northeast"></el-option>
						</el-select>
					</div>
					<div class="form-item">
						<label class="form-label">时间范围</label>
						<el-date-picker
							v-model="searchForm.dateRange"
							type="daterange"
							range-separator="至"
							start-placeholder="开始日期"
							end-placeholder="结束日期"
							:picker-options="datePickerOptions">
						</el-date-picker>
					</div>
					<div class="form-item">
						<label class="form-label">数据粒度</label>
						<el-select v-model="searchForm.granularity" placeholder="选择粒度">
							<el-option label="按日" value="daily"></el-option>
							<el-option label="按周" value="weekly"></el-option>
							<el-option label="按月" value="monthly"></el-option>
						</el-select>
					</div>
					<div class="form-item">
						<el-button type="primary" @click="searchData" :loading="searching">
							<i class="el-icon-search"></i> 查询数据
						</el-button>
						<el-button @click="resetForm">重置</el-button>
					</div>
				</div>
			</div>

			<!-- 查询结果 -->
			<div class="results-panel" v-if="hasSearched">
				<div class="results-header">
					<div class="results-title">
						<i class="el-icon-data-line"></i>
						查询结果
					</div>
					<div>
						<el-button size="small" @click="exportData">导出数据</el-button>
					</div>
				</div>
				<div class="results-content">
					<!-- 加载状态 -->
					<div v-if="searching" class="loading-state">
						<i class="el-icon-loading" style="font-size: 32px; margin-bottom: 10px;"></i>
						<p>正在查询历史数据...</p>
					</div>

					<!-- 无数据状态 -->
					<div v-else-if="!historyData || historyData.length === 0" class="no-data">
						<i class="el-icon-document" style="font-size: 48px; color: #ddd; margin-bottom: 15px;"></i>
						<p>未找到符合条件的历史数据</p>
						<el-button size="small" @click="resetForm">重新查询</el-button>
					</div>

					<!-- 数据展示 -->
					<div v-else>
						<!-- 统计摘要 -->
						<div class="statistics-summary">
							<div class="summary-item">
								<div class="summary-value">{{statistics.avgPrice}}</div>
								<div class="summary-label">平均价格</div>
							</div>
							<div class="summary-item">
								<div class="summary-value">{{statistics.maxPrice}}</div>
								<div class="summary-label">最高价格</div>
							</div>
							<div class="summary-item">
								<div class="summary-value">{{statistics.minPrice}}</div>
								<div class="summary-label">最低价格</div>
							</div>
							<div class="summary-item">
								<div class="summary-value">{{statistics.priceChange}}</div>
								<div class="summary-label">价格变化</div>
							</div>
							<div class="summary-item">
								<div class="summary-value">{{statistics.volatility}}</div>
								<div class="summary-label">波动率</div>
							</div>
							<div class="summary-item">
								<div class="summary-value">{{statistics.dataPoints}}</div>
								<div class="summary-label">数据点数</div>
							</div>
						</div>

						<!-- 图表切换 -->
						<el-tabs v-model="activeChart" @tab-click="switchChart">
							<el-tab-pane label="价格走势" name="trend">
								<div id="trendChart" class="chart-container"></div>
							</el-tab-pane>
							<el-tab-pane label="波动分析" name="volatility">
								<div id="volatilityChart" class="chart-container"></div>
							</el-tab-pane>
							<el-tab-pane label="成交量" name="volume">
								<div id="volumeChart" class="chart-container"></div>
							</el-tab-pane>
							<el-tab-pane label="数据表格" name="table">
								<el-table :data="historyData" style="width: 100%" max-height="400">
									<el-table-column prop="date" label="日期" width="120"></el-table-column>
									<el-table-column prop="product" label="商品"></el-table-column>
									<el-table-column prop="price" label="价格" width="100">
										<template slot-scope="scope">
											¥{{scope.row.price}}
										</template>
									</el-table-column>
									<el-table-column prop="change" label="涨跌" width="100">
										<template slot-scope="scope">
											<span :class="['trend-indicator', scope.row.change > 0 ? 'trend-up' : scope.row.change < 0 ? 'trend-down' : 'trend-stable']">
												<i :class="scope.row.change > 0 ? 'el-icon-top' : scope.row.change < 0 ? 'el-icon-bottom' : 'el-icon-minus'"></i>
												{{scope.row.change > 0 ? '+' : ''}}{{scope.row.change}}%
											</span>
										</template>
									</el-table-column>
									<el-table-column prop="volume" label="成交量" width="100"></el-table-column>
									<el-table-column prop="region" label="地区"></el-table-column>
								</el-table>
							</el-tab-pane>
						</el-tabs>
					</div>
				</div>
			</div>

			<!-- 对比分析 -->
			<div class="compare-section" v-if="hasSearched && historyData && historyData.length > 0">
				<div class="compare-title">
					<i class="el-icon-s-data"></i>
					对比分析
				</div>
				<div class="compare-controls">
					<span>对比维度：</span>
					<el-radio-group v-model="compareMode" @change="updateCompareChart">
						<el-radio-button label="period">时期对比</el-radio-button>
						<el-radio-button label="product">商品对比</el-radio-button>
						<el-radio-button label="region">地区对比</el-radio-button>
					</el-radio-group>
					<el-button size="small" @click="addCompareItem">添加对比项</el-button>
				</div>
				<div id="compareChart" class="compare-chart"></div>
			</div>
		</div>
	</div>

	<!-- 引入依赖 -->
	<script src="https://unpkg.com/vue@2.6.10/dist/vue.js"></script>
	<script src="https://unpkg.com/element-ui@2.13.0/lib/index.js"></script>
	<script>
		new Vue({
			el: '#app',
			data() {
				return {
					searchForm: {
						category: [],
						product: [],
						region: 'national',
						dateRange: [],
						granularity: 'daily'
					},
					searching: false,
					hasSearched: false,
					activeChart: 'trend',
					compareMode: 'period',
					availableProducts: [
						{label: '有机小白菜', value: 'organic_cabbage'},
						{label: '西兰花', value: 'broccoli'},
						{label: '澳洲牛肉', value: 'aussie_beef'},
						{label: '三文鱼', value: 'salmon'},
						{label: '帝王蟹', value: 'king_crab'},
						{label: '冷冻虾仁', value: 'frozen_shrimp'}
					],
					datePickerOptions: {
						shortcuts: [{
							text: '最近一周',
							onClick(picker) {
								const end = new Date();
								const start = new Date();
								start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
								picker.$emit('pick', [start, end]);
							}
						}, {
							text: '最近一个月',
							onClick(picker) {
								const end = new Date();
								const start = new Date();
								start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
								picker.$emit('pick', [start, end]);
							}
						}, {
							text: '最近三个月',
							onClick(picker) {
								const end = new Date();
								const start = new Date();
								start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
								picker.$emit('pick', [start, end]);
							}
						}]
					},
					historyData: [],
					statistics: {
						avgPrice: '¥0',
						maxPrice: '¥0',
						minPrice: '¥0',
						priceChange: '0%',
						volatility: '0%',
						dataPoints: 0
					},
					charts: {}
				}
			},
			methods: {
				searchData() {
					if (!this.searchForm.dateRange || this.searchForm.dateRange.length === 0) {
						this.$message.warning('请选择查询时间范围');
						return;
					}
					
					this.searching = true;
					this.hasSearched = true;
					
					// 模拟API请求
					setTimeout(() => {
						this.historyData = this.generateMockData();
						this.calculateStatistics();
						this.searching = false;
						
						this.$nextTick(() => {
							this.initCharts();
						});
					}, 2000);
				},
				
				generateMockData() {
					const data = [];
					const startDate = new Date(this.searchForm.dateRange[0]);
					const endDate = new Date(this.searchForm.dateRange[1]);
					const products = this.searchForm.product.length > 0 ? this.searchForm.product : ['organic_cabbage'];
					
					for (let d = new Date(startDate); d <= endDate; d.setDate(d.getDate() + 1)) {
						products.forEach(product => {
							const basePrice = Math.random() * 50 + 20;
							const change = (Math.random() - 0.5) * 20;
							data.push({
								date: d.toISOString().split('T')[0],
								product: this.getProductName(product),
								price: basePrice.toFixed(2),
								change: change.toFixed(1),
								volume: Math.floor(Math.random() * 1000) + 100,
								region: this.getRegionName(this.searchForm.region)
							});
						});
					}
					return data;
				},
				
				getProductName(value) {
					const product = this.availableProducts.find(p => p.value === value);
					return product ? product.label : value;
				},
				
				getRegionName(value) {
					const regions = {
						'national': '全国',
						'north': '华北地区',
						'east': '华东地区',
						'south': '华南地区',
						'central': '华中地区',
						'southwest': '西南地区',
						'northwest': '西北地区',
						'northeast': '东北地区'
					};
					return regions[value] || value;
				},
				
				calculateStatistics() {
					if (this.historyData.length === 0) return;
					
					const prices = this.historyData.map(item => parseFloat(item.price));
					const avgPrice = (prices.reduce((sum, price) => sum + price, 0) / prices.length).toFixed(2);
					const maxPrice = Math.max(...prices).toFixed(2);
					const minPrice = Math.min(...prices).toFixed(2);
					
					const firstPrice = prices[0];
					const lastPrice = prices[prices.length - 1];
					const priceChange = (((lastPrice - firstPrice) / firstPrice) * 100).toFixed(1);
					
					// 计算波动率
					const returns = [];
					for (let i = 1; i < prices.length; i++) {
						returns.push((prices[i] - prices[i-1]) / prices[i-1]);
					}
					const volatility = (Math.sqrt(returns.reduce((sum, ret) => sum + ret * ret, 0) / returns.length) * 100).toFixed(1);
					
					this.statistics = {
						avgPrice: `¥${avgPrice}`,
						maxPrice: `¥${maxPrice}`,
						minPrice: `¥${minPrice}`,
						priceChange: `${priceChange > 0 ? '+' : ''}${priceChange}%`,
						volatility: `${volatility}%`,
						dataPoints: this.historyData.length
					};
				},
				
				initCharts() {
					this.initTrendChart();
					this.initVolatilityChart();
					this.initVolumeChart();
					this.initCompareChart();
				},
				
				initTrendChart() {
					const chart = echarts.init(document.getElementById('trendChart'));
					const dates = [...new Set(this.historyData.map(item => item.date))];
					const products = [...new Set(this.historyData.map(item => item.product))];
					
					const series = products.map(product => {
						const productData = this.historyData
							.filter(item => item.product === product)
							.map(item => parseFloat(item.price));
						
						return {
							name: product,
							type: 'line',
							smooth: true,
							data: productData
						};
					});
					
					const option = {
						tooltip: {
							trigger: 'axis',
							axisPointer: { type: 'cross' }
						},
						legend: { data: products },
						grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
						xAxis: {
							type: 'category',
							data: dates
						},
						yAxis: { type: 'value', name: '价格(元)' },
						series: series
					};
					
					chart.setOption(option);
					this.charts.trendChart = chart;
				},
				
				initVolatilityChart() {
					const chart = echarts.init(document.getElementById('volatilityChart'));
					const products = [...new Set(this.historyData.map(item => item.product))];
					const volatilityData = products.map(product => {
						const productPrices = this.historyData
							.filter(item => item.product === product)
							.map(item => parseFloat(item.price));
						
						const returns = [];
						for (let i = 1; i < productPrices.length; i++) {
							returns.push(Math.abs((productPrices[i] - productPrices[i-1]) / productPrices[i-1]));
						}
						const avgVolatility = returns.reduce((sum, ret) => sum + ret, 0) / returns.length * 100;
						return avgVolatility.toFixed(2);
					});
					
					const option = {
						tooltip: { trigger: 'axis' },
						grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
						xAxis: {
							type: 'category',
							data: products
						},
						yAxis: { type: 'value', name: '波动率(%)' },
						series: [{
							name: '波动率',
							type: 'bar',
							data: volatilityData,
							itemStyle: { color: '#409eff' }
						}]
					};
					
					chart.setOption(option);
					this.charts.volatilityChart = chart;
				},
				
				initVolumeChart() {
					const chart = echarts.init(document.getElementById('volumeChart'));
					const dates = [...new Set(this.historyData.map(item => item.date))];
					const volumeData = dates.map(date => {
						return this.historyData
							.filter(item => item.date === date)
							.reduce((sum, item) => sum + parseInt(item.volume), 0);
					});
					
					const option = {
						tooltip: { trigger: 'axis' },
						grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
						xAxis: {
							type: 'category',
							data: dates
						},
						yAxis: { type: 'value', name: '成交量' },
						series: [{
							name: '成交量',
							type: 'bar',
							data: volumeData,
							itemStyle: { color: '#67c23a' }
						}]
					};
					
					chart.setOption(option);
					this.charts.volumeChart = chart;
				},
				
				initCompareChart() {
					const chart = echarts.init(document.getElementById('compareChart'));
					// 简单的对比图表示例
					const option = {
						tooltip: { trigger: 'axis' },
						legend: { data: ['对比项1', '对比项2'] },
						grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
						xAxis: {
							type: 'category',
							data: ['1月', '2月', '3月', '4月', '5月', '6月']
						},
						yAxis: { type: 'value' },
						series: [
							{
								name: '对比项1',
								type: 'line',
								data: [120, 132, 101, 134, 90, 230]
							},
							{
								name: '对比项2',
								type: 'line',
								data: [220, 182, 191, 234, 290, 330]
							}
						]
					};
					
					chart.setOption(option);
					this.charts.compareChart = chart;
				},
				
				switchChart(tab) {
					this.$nextTick(() => {
						if (this.charts[tab.name + 'Chart']) {
							this.charts[tab.name + 'Chart'].resize();
						}
					});
				},
				
				updateCompareChart() {
					this.$message.info(`切换到${this.compareMode}对比模式`);
					// 实际应用中这里会更新对比图表
				},
				
				addCompareItem() {
					this.$message.info('添加对比项功能');
					// 实际应用中这里会打开对比项选择弹窗
				},
				
				exportData() {
					this.$message.success('数据导出功能');
					// 实际应用中这里会导出Excel或CSV文件
				},
				
				resetForm() {
					this.searchForm = {
						category: [],
						product: [],
						region: 'national',
						dateRange: [],
						granularity: 'daily'
					};
					this.hasSearched = false;
					this.historyData = [];
				},
				
				resizeCharts() {
					Object.values(this.charts).forEach(chart => {
						chart.resize();
					});
				}
			},
			mounted() {
				window.addEventListener('resize', this.resizeCharts);
			},
			beforeDestroy() {
				window.removeEventListener('resize', this.resizeCharts);
				Object.values(this.charts).forEach(chart => {
					chart.dispose();
				});
			}
		});
	</script>
</body>
</html>